#coding=utf-8
'''
Created on 2018-3-9

@author: Administrator
'''
from selenium import webdriver
import time
import os
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import sys
import xlrd
import pymysql
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
# class global_variable:
#     def variable_name(self):
#         self.results
class Browser():
    def __init__(self):
        self.timeout=10
        self.driver=None
    def startFirefox(self,url):
        self.driver=webdriver.Firefox()
        self.driver.get(url)
        self.driver.maximize_window()

    def startIE(self,url):
        ie_driver = sys.executable
        print ("ie_driver:"),ie_driver
        ie_driver=ie_driver.lower().replace('python.exe', 'IEDriverServer.exe')
        self.driver = webdriver.Ie(ie_driver)
        self.driver.get(url)
        self.driver.maximize_window()

    def startChrome(self,url):
        chromedriver = "C:\\Users\Administrator\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe"
        print ("chromedriver:"),chromedriver
        os.environ["webdriver.chrome.driver"] = chromedriver
        self.driver = webdriver.Chrome(chromedriver)
        self.driver.get(url)
        self.driver.maximize_window()
        # chrome_driver = sys.executable
        # print "chrome_driver:",chrome_driver
        # chrome_driver=chrome_driver.lower().replace('python.exe', 'chromedriver.exe')
        # self.driver = webdriver.Chrome(chrome_driver)
        # self.driver.get(URL)
        # self.driver.maximize_window()

    def open_url(self,driver,url):
        self.driver.get(url)
        return True

    def input_byid(self,local,para):
        self.driver.find_element_by_id(local).send_keys(para)
        return True
    def input_byname(self,local,para):
        self.driver.find_element_by_name(local).send_keys(para)
        return True

    def element(func):  # 装饰器
        def deco(*args, **kwargs):
            try:
                func(*args, **kwargs)
            except:
                print("element not exit")
            # return func
        return deco

    # @element
    def input_byxpath(self,local,para):
        # self.driver.find_element_by_xpath(local).send_keys(para)
        # return True
        try:
            self.driver.find_element_by_xpath(local).send_keys(para)
            # print('input %s success' % para)
            return True
        except:
            print("\033[0;31m%s not found" % local)  # 红色字体
            # self.driver.quit()
    @element
    def input_byclass(self,local,para):
        self.driver.find_element_by_class_name(local).send_keys(para)
        return True
    @element
    def click_byid(self,local):
        self.driver.find_element_by_id(local).click()
        return True
    @element
    def click_byname(self,local):
        self.driver.find_element_by_name(local).click()
        return True
    @element
    def click_byxpath(self,local):
        # self.driver.find_element_by_xpath(local).click()
        # return True
        try:
            self.driver.find_element_by_xpath(local).click()
            # print("click %s success" % local)
            return True
        except:
            # print("%s not found"%local)
            print("\033[0;31m%s not found" % local)  # 红色字体
            # self.driver.quit()

    def click_byclassname(self,local):
        self.driver.find_element_by_class_name(local).click()
        return True
    def click_bylinktext(self,local):
        self.driver.find_element_by_link_text(local).click()
        return True
#    def get_text_byxpath(self,local):
#        self.driver.find_element_by_xpath(local).text
#        return True
        
    def is_visible(self,local):
        try:
            WebDriverWait(self.driver, self.timeout).until(EC.visibility_of_element_located(local))
            return True
        except:
            print ("error")
            return False

    def isElementExist(self, local):#判断页面元素是否存在
        flag = True
        try:
            self.driver.find_element_by_xpath(local)
            return flag
        except:
            flag = False
            return flag
    def close_Browser(self):
        self.driver.quit()

    def execute_javascript(self, *code):
        """Executes the given JavaScript code.

        `code` may contain multiple lines of code and may be divided into
        multiple cells in the test data. In that case, the parts are
        catenated together without adding spaces.

        If `code` is an absolute path to an existing file, the JavaScript
        to execute will be read from that file. Forward slashes work as
        a path separator on all operating systems.

        The JavaScript executes in the context of the currently selected
        frame or window as the body of an anonymous function. Use _window_ to
        refer to the window of your application and _document_ to refer to the
        document object of the current frame or window, e.g.
        _document.getElementById('foo')_.

        This keyword returns None unless there is a return statement in the
        JavaScript. Return values are converted to the appropriate type in
        Python, including WebElements.

        Examples:
        | Execute JavaScript | window.my_js_function('arg1', 'arg2') |               |
        | Execute JavaScript | ${CURDIR}/js_to_execute.js            |               |
        | ${sum}=            | Execute JavaScript                    | return 1 + 1; |
        | Should Be Equal    | ${sum}                                | ${2}          |
        """
        js = self._get_javascript_to_execute(''.join(code))
        self._info("Executing JavaScript:\n%s" % js)
        return self._current_browser().execute_script(js)


    def _get_javascript_to_execute(self, code):
        codepath = code.replace('/', os.sep)
        if not (os.path.isabs(codepath) and os.path.isfile(codepath)):
            return code
        self._html('Reading JavaScript from file <a href="file://%s">%s</a>.'
                   % (codepath.replace(os.sep, '/'), codepath))
        codefile = open(codepath)
        try:
            return codefile.read().strip()
        finally:
            codefile.close()
            
    def assert_if_true(self,local,texts):
        error_mes=self.driver.find_element_by_xpath(local).text
        print (error_mes)
        print (texts)
        try:
            # assert error_mes==texts#设置变量
            assert texts in error_mes#判断提取值包含断言值
            print('Assert Test Pass !')
            time.sleep(1)
        except Exception as e:
            print(' Assert Test fail !!.',format(e))


    def screenshot_image(self,pic_path,pic_name):#使用中
        now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
        # pic_path = "D://My//Backend//" + now + '.png'
        # pic_name= '编辑前服务商信息' + now + '.png'
        pic_path_all=pic_path+ now
        pic_name_all=pic_name+ '.png'
        pic = pic_path_all + pic_name_all
        print(pic)
        print(self.driver.title)
        time.sleep(1)
        self.driver.save_screenshot(pic)
        name=self.driver.save_screenshot(pic)

    def screenshot(self):
        imageName = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) + '.png '  # 用时间戳定义截图名称
        imagepath = '//sdcard//' + imageName  # 手机-保存截图地址
        path = os.getcwd() + '\\screenshot'  # 本地-保存截图地址
        if not os.path.exists(path):  # 判断地址是否有效，如果不存在就创建一个地址
            os.mkdir(path)
        os.system("adb shell //system//bin//screencap -p " + imagepath)
        os.system('adb pull ' + imagepath + path)
        screenshotUrl = path + '\\' + imageName  # 获取具体图片的地址
        #       print('lustrat' + screenshotUrl  + 'luend')


class Testdata():
    def excel_table_byindex(self,file,colnameindex):#根据索引获取excel表格中的数据，file:excel文件路径，colnameindex:表头列各所在行的
        data=xlrd.open_workbook(file)
        table=data.sheets()[0]
        nrows=table.nrows#行数
        colnames=table.row_values(colnameindex)#某一行数据
        list=[]
        for colnameindex in range(1,nrows):
            row=table.row_values(colnameindex)
            if row:
                app={}
                for i in range(len(colnames)):
                    app[colnames[i]]=str(row[i])
                list.append(app)
        return list


    def connect_db(self,database,sql,charset='utf8'):
        # global results#定义全局变量
        self.conn=pymysql.connect(host="115.159.76.132",port=3306,user="devroot",passwd="devroot@123",db=database,charset='utf8')
        # self.cur = self.conn.cursor(pymysql.cursors.DictCursor)#带有键值对的数组
        self.cur=self.conn.cursor()
        self.cur.execute(sql)  # 执行sql语句
        self.conn.commit()  # 提交事务
        results=self.cur.fetchall()
        # print(results)
        return results
        # print(results[0][1])
    # 判断数据库数据是否正确
    def assert_data(self, data, texts):
        try:
            assert data == texts
            print("数据库的值:%s"%data)
            print("断言值:%s"%texts)
            print('data assert passed!')
        except:
            print("数据与预期不一致")

if __name__=="__main__":
#     # provider_name='zdhcs1'
    B=Browser()
    T=Testdata()

    # database = 'fpmerchant'
    # sql = "select state,tax_code,name from m_sell_client where tax_code='GAOPENG2018041705'"
    # T.connect_db(database,sql,charset='utf8')
    # print(results[0][2])
    # # if T.connect_db(database='fpmerchant',sql="select tax_code from m_sell_client where tax_code='GAOPENG2018041608'")!=0:
    # #     print(1)
    # # else:
    # #     print(2)
    # B.assert_data(data=results[0][2],texts='接口商户')

    # database = 'fpmerchant'
    # sql = "select state,register_status,name,tax_code from m_sell_client where tax_code='GAOPENG2018041705'"
    # r=T.connect_db(database, sql)
    # T.assert_data(data=r[0][0], texts=1)
    # print('商户状态正确')
    # T.assert_data(data=r[0][1], texts=1)
    # print('商户注册状态正确')

    r=T.connect_db(database='privilege',sql="select id from qx_member where email='958266305@qq.com'")
    print(r[0][0])

    print("<h1>test<h1/>")# 红色字体
#     # database = 'providers_db'
#     # sql = "select app_id,name from gpi_provider where name='%s'"%provider_name
#     database='settlement'
#     sql='show tables'
#     # sql="update s_settlement set status=4 where stat_id=41 "
#
#     # # sql="show tables"
#     T.connect_db(database, sql)
#     # input_bypath=element(input_byxpath)
#     # B=Browser()
#     # B.input_byxpath()




        
        
        